const model = require("../models/userModel");
const JWT = require("../utils/jwtUtil");

/* 实际处理注册请求 */
async function register({ username, password }) {
    // 首先查询用户名是否存在
    const users = await model.getUser({ username });
    console.log("register:existedUsers=", users);
    if (!users.length) {
        return model.addUser({ username, password });
    } else {
        return Promise.resolve({ msg: "用户名已存在" });
    }
}

/* 实际处理登录请求 */
async function login({ username, password }) {
    const users = await model.getUser({ username, password });
    console.log("register:existedUsers=", users);

    // 如果登录成功 记录之
    let token = null;
    if (users.length) {
        token = JWT.generate({ username, password });
        console.log("login:token=", token);
    }

    return Promise.resolve({
        code: users.length > 0 ? 1 : 0,
        msg: users.length > 0 ? "登录成功" : "登录失败",
        token,
    });
}

/* 更新用户信息 */
async function updateUser(id,user){
    return model.updateUser(id,user)
}

/* 获取用户信息 */
async function getUser(user){
    return model.getUser(user)
}

module.exports = {
    register,
    login,
    updateUser,
    getUser
};
